//基于 Web IM SDK 封装的聊天室中间层示例

;(function (global, factory, namespace) {
    if(typeof exports === 'object' && typeof module !== 'undefined'){
    	module.exports = factory();
    }else if(typeof define === 'function' && define.amd){
    	define(factory);
    }else{
    	global[namespace] = factory();
    }
})(window, function(){
	"use strict";

	function initApp(appInfo, callbacks, modules){

		window.RongIM = window.RongIM || {};

		//缓存消息回调队列
		window.onMessageList = window.onMessageList || [];
		window.onMessageList.push(callbacks.onMessage);

		//缓存状态队列
		window.onConnectList = window.onConnectList || [];
		window.onConnectList.push(callbacks.onConnected);

		modules = modules || {};
		var RongIMLib = modules.RongIMLib || window.RongIMLib;
		var RongIMClient = RongIMLib.RongIMClient;

		if(RongIM.ready){
			callbacks.onReady && callbacks.onReady(RongIM.instance);
			callbacks.onConnected && callbacks.onConnected(RongIM.instance, RongIM.userInfo);
			return;
		}else{
			var appKey = appInfo.appKey;
			var token = appInfo.token;
			var navi = appInfo.navi || "";

			var protobuf = modules.protobuf || null;

			var config = {};

			//私有云
			if(navi !== ""){
				config.navi = navi;
			}

			//support protobuf url + module
			if(protobuf != null){
				config.protobuf = protobuf;
			};

			RongIMLib.RongIMClient.init('p5tvi9dspqkw4',null,config);
	
			//开始链接
			var token = localStorage.getItem('token');
			RongIMClient.connect(token, {
				onSuccess: function(userId) {
					
				},
				onTokenIncorrect: function() {
			
				},
				onError:function(errorCode){
					
				}
			});
		}
		var friend_id_active = $(document).find('.main_left').children().html()
//		console.log(friend_id_active)
		// 连接状态监听器
		RongIMClient.setConnectionStatusListener({
			onChanged: function (status) {
//				console.log('status'+status);
			     switch (status) {
		            case RongIMLib.ConnectionStatus.CONNECTED:
//		                console.log('链接成功');
		                break;
		            case RongIMLib.ConnectionStatus.CONNECTING:
//		                console.log('正在链接');
		                break;
		            case RongIMLib.ConnectionStatus.DISCONNECTED:
//		                console.log('断开连接');
		                break;
		            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
//		                console.log('其他设备登录');
		                break;
		            case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
//		                console.log('域名不正确');
		                break;
		            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
//		                console.log('网络不可用');
		                break;
		        }
			}
		});
        // 接收消息
		RongIMClient.setOnReceiveMessageListener({
			// 接收到的消息
			onReceived: function (message) {
			    // 判断消息类型
//			    console.log(message)
				console.log("新消息: " + message.targetId);
				
				//type_xt 为2有好友申请   type为1是系统消息
				var type_xt = message.content.extra
				if(!type_xt || type_xt=="undefined" || type_xt=="null"){
					type_xt = ''
				}
//				console.log(type_xt)
				if(type_xt!=''){
					if(type_xt.type){
						var html_xt='';
						switch (type_xt.type){
							case 2:
							html_xt+='<dl class="clearfix msg_left ">'+
										'<dt class="left"><img class="msg_head" src="img/icon_cx.png"/></dt>'+
										'<dd class="left">'+
											'<div class="msg_box relative">'+
												'<i class="absolute"></i>'+
												'<span class="msg_font">'+ message.content.content +'</span>'+
											'</div>'+
										'</dd>'+
									'</dl>'
									$('.msg_content').append(html_xt)
								break;
							case 1:
							$('#new_friends').children('.bage').show()
								break;	
							default:
								break;
						}
					}
					
			   }else{
				if(message.conversationType==1){//单聊
//					console.log('单聊')
					var friend_list = $('.main_left').find('.mian_friends').find('.friends_list li')
					var friend_id_active = $('#chat_id').val()
//				    console.log('好友id'+friend_id_active)
					if(friend_id_active == message.targetId){
						var head=$('.friends_list li.active').children('dl').find('dt').find('.friends_head').attr('src')
						var html_friend='';
						//文本
					    if(message.content.messageName =='TextMessage'){
					    	html_friend += '<dl class="clearfix msg_left ">'+
								'<dt class="left"><img class="msg_head" src="'+head+'"/></dt>'+
								'<dd class="left">'+
									'<div class="msg_box relative">'+
										'<i class="absolute"></i>'+
										'<span class="msg_font">'+RongIMLib.RongIMEmoji.emojiToHTML(message.content.content)+'</span>'+
									'</div>'+
								'</dd>'+
							'</dl>'	;
					    }else if(message.content.messageName == 'ImageMessage'){//图片
					    	html_friend +='<dl class="clearfix msg_left">'+
								'<dt class="left"><img class="msg_head" src="'+head+'"/></dt>'+
								'<dd class="left">'+
									'<div class="msg_box relative">'+
										'<i class="absolute"></i>'+
										'<span class="msg_font"><img src="'+message.content.imageUri+'"/></span>'+
									'</div>'+
								'</dd>'+
							'</dl>'	
					    }else if(message.content.messageName =='VoiceMessage'){//语音
					    	html_friend +='<p class="text-center color_9 padding_tb10">收到语音 请在手机上查看</p>'
					    	
//					    	var audioFile =message.content.content
//					    	var duration = audioFile.length / 1024;
//// 预加载                                            
//							RongIMLib.RongIMVoice.preLoaded(audioFile, function(){
//							    // 播放声音
//							    RongIMLib.RongIMVoice.play(audioFile, duration);
//							});
					    }else if(message.content.messageName =='UnknownMessage'){//红包//名片
					    	var type_name=message.objectName
//					    	console.log(type_name)
					    	switch (type_name){
					    		case 'RC:CardMsg':
					    		html_friend +='<p class="text-center color_9 padding_tb10">收到名片 请在手机上查看</p>'	
					    			break;
					    		case 'IHC:RedPacketMsg':
					    		html_friend +='<p class="text-center color_9 padding_tb10">收到红包 请在手机上查看</p>'	
					    			break;	
					    		default:
					    			break;
					    	}
					    	
					    	
					    }
					    $('.msg_content').append(html_friend)
					}else{
						$.each(friend_list, function() {
							if($(this).attr('data-friendid')==message.targetId){
							   var count = getnews(message.targetId,message.conversationType)
//							   
							}
						});
						$('.msg_content').append(html_friend)
					}
				
				   
				}
			
	        }

			}
		});
		


	}
	//获取指定会话总数
    function getnews(friend_id,conversationType){
    	
    	console.log(friend_id)
		var targetId = friend_id;
		RongIMLib.RongIMClient.getInstance().getUnreadCount(conversationType, targetId, {
		    onSuccess: function(count){
		    	if(conversationType==1){
		    		var friend_list = $('.main_left').find('.mian_friends').find('.friends_list li')
			    	 $.each(friend_list, function() {
			    	 	if($(this).attr('data-friendid')== friend_id){
			    	 		$(this).children('.bage').show().text(count)
			    	 	}
			    	 });
		    	}else if(conversationType==3){
		    		$.each(qun_list, function() {
			    	 	if($(this).attr('data-chatid')== friend_id){
			    	 		console.log('群聊未读消息：'+count)
			    	 		$(this).children('a').find('dl').find('.bage').show().text(count)
			    	 	}
			    	 });
		    	}
		    	 
		        // count => 指定会话的总未读数
		        return count
		        
		       
		       
		    },
		    onError: function(){
		        // error => 获取指定会话未读数错误码
		    }
		});
    }
	//清除未读消息
    function clearnews(friend_id){
    	var conversationType = RongIMLib.ConversationType.PRIVATE;
		var targetId = friend_id;
		RongIMClient.getInstance().clearUnreadCount(conversationType, targetId, {
		    onSuccess: function(){
		    	this.find('.bage').hide().text('')
		        // 清除未读消息成功
		    },
		    onError: function(error){
		        // error => 清除未读消息数错误码
		    }
		});
    }
    
    
    
    
	function initChatRoom(appInfo, chatRoomInfo, callbacks, modules){
		var chatRoomId = chatRoomInfo.chatRoomId;
		var count = chatRoomInfo.count;

		window.chatRoomCallbacks = {};

		//公有云初始化
		var config = {
	        //protobuf: './local-sdk/protobuf-2.2.7.min.js' //支持http(s)网络路径、本地相对路径
	    };

		var initCallbacks = {
			onReady : function(_instance){

			},
			onMessage : function(message){
				// 判断消息类型
	            var onMessage = callbacks.onMessage;
            	if (message.conversationType == 4 && message.targetId == chatRoomId) {
            		if(message.senderUserId != 'admin'){
                        getUserInfos([message.senderUserId],function (data) {
                            message.username = data.username;
                            message.head = data.head;
                        });
					}

	            	onMessage(message);
	            }
			},
			onConnected : function(IM, userInfo){
				//链接成功
				
			}
		};
		initApp(appInfo, initCallbacks, config);
	}
    return {
		init : initChatRoom
	};
}, "RongChatRoom");
     //发送信息
    function sendMessage(type) {
//  	console.log(type)
    	var msg = $(".msg_inp").text()
    	
    	msg = RongIMLib.RongIMEmoji.symbolToEmoji(msg);
//  	console.log(msg)
    	
    	var msg1 = new RongIMLib.TextMessage({ content: msg,} );

		if(type==1){
			var conversationType = RongIMLib.ConversationType.PRIVATE;
		}else if(type==3){
			var conversationType = RongIMLib.ConversationType.GROUP;
		}
		var targetId=$('#chat_id').val().toString()
//		console.log(targetId)
    	if(targetId=''){
    		msg("请选择聊天对象")
    		return false;
    	}
    				
        RongIMClient.getInstance().sendMessage(conversationType, $('#chat_id').val().toString(), msg1, {
            // 发送消息成功
            onSuccess: function (message) {
            	var head =localStorage.getItem('myhead')
         		 $(".msg_inp").html('')
//	            		var extra = eval('(' + message.content.extra + ')');
	                var str='<dl class="clearfix msg_right  text_right" >' +
							'<dt class="right"><img class="msg_head" src="'+head+'"/></dt>' +
							'<dd class="right">' +
								'<div class="msg_box relative">' +
									'<i class="absolute"></i>' +
									'<span class="msg_font">'+ RongIMLib.RongIMEmoji.emojiToHTML(message.content.content)+'</span>' +
								'</div>' +
							'</dd>' +
						'</dl>'
	                $('.msg_content').append(str);
	                $('.msg_content').scrollTop($('.msg_content')[0].scrollHeight);
                
//              console.log(message)
            },
            onError: function (errorCode, message) {
//              console.log('errorCode:'+errorCode);
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    case 23408:
                        info = 23408;
                        break;
                    default:
                        info = "x";
                        break;
                }
                if (info == 23408){
                    layer.msg('您已被禁言,不能发送消息!', {icon: 0});
                }
//              console.log('发送失败:' + info);
                 msg('发送失败:' + info)
            }
        });
    }

	
    //发送图片
    function sendImg(type,url,sendData) {
//      console.log(sendData)
    	var msg = new RongIMLib.ImageMessage({content:sendData , imageUri: url,extra:{
    		head:localStorage.getItem('myhead')
    	}});
		if(type==1){
			var conversationType = RongIMLib.ConversationType.PRIVATE;
		}else if(type==3){
			var conversationType = RongIMLib.ConversationType.GROUP;
		}
		var targetId=$('#chat_id').val().toString()
//		console.log(targetId)
    	if(targetId=''){
    		msg("请选择聊天对象")
    		return false;
    	}
    				
        RongIMClient.getInstance().sendMessage(conversationType, $('#chat_id').val().toString(), msg, {
            // 发送消息成功
            onSuccess: function (message) {
//          	console.log(targetId)
         		 $(".msg_inp").html('')
//	            		var extra = eval('(' + message.content.extra + ')');
	                var str='<dl class="clearfix msg_right  text_right" >' +
							'<dt class="right"><img class="msg_head" src="'+message.content.extra.head+'"/></dt>' +
							'<dd class="right">' +
								'<div class="msg_box relative">' +
									'<i class="absolute"></i>' +
									'<span class="msg_font"><img class="" src="'+message.content.imageUri+'"/> </span>' +
								'</div>' +
							'</dd>' +
						'</dl>'
	                $('.msg_content').append(str);
	                $('.msg_content').scrollTop($('.msg_content')[0].scrollHeight);
                
               
            },
            onError: function (errorCode, message) {
                console.log('errorCode:'+errorCode);
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    case 23408:
                        info = 23408;
                        break;
                    default:
                        info = "x";
                        break;
                }
                if (info == 23408){
                    layer.msg('您已被禁言,不能发送消息!', {icon: 0});
                }
                console.log('发送失败:' + info);
                msg('发送失败:' + info)
            }
        });
    }
    
    function acceptMsg(message){
		console.log(message)
		var friend_list = $('.main_left').find('.mian_friends').find('.friends_list li')
		var friend_id = $('.main_left').find('.mian_friends').find('.friends_list li').attr('data-friendid')
		var friend_id_active = $('.main_left').find('.mian_friends').find('.friends_list li.active').attr('data-friendid')
//		console.log(friend_id_active)
		if(message.content.messageName == 'TextMessage'){
//		    	console.log('TextMessage')
		    	html_friend+='<dl class="clearfix msg_left ">'+
					'<dt class="left"><img class="msg_head" src="'+head+'"/></dt>'+
					'<dd class="left">'+
						'<div class="msg_box relative">'+
							'<i class="absolute"></i>'+
							'<span class="msg_font">'+RongIMLib.RongIMEmoji.emojiToHTML(message.content.content)+'</span>'+
						'</div>'+
					'</dd>'+
				'</dl>'	
		    	
		    }else if(message.content.messageName == 'ImageMessage'){//图片
		    	html_friend+='<dl class="clearfix msg_left ">'+
					'<dt class="left"><img class="msg_head" src="'+head+'"/></dt>'+
					'<dd class="left">'+
						'<div class="msg_box relative">'+
							'<i class="absolute"></i>'+
							'<span class="msg_font">'+message.content.imageUri+'</span>'+
						'</div>'+
					'</dd>'+
				'</dl>'	
		    }
		} 
		//获取群成员
	function groupMember(chat_id,member_id){
			$.ajax({
          	headers:{'token':localStorage.getItem('user_token')},
			type: "post",
			url: urlcom + "user/groupMember",
			async:true,
			dataType: 'json',
			data: {
				chat_id: chat_id,
				member_id: member_id
			},
			success: function(res) {
				if(res.code == 1) {
					window.localStorage.setItem('sendhead', res.data[0].user.avatar);
					
				}else{
					msg(res.msg)
				}
			}
		});
	}
